package com.jt.www.biz.pay.controller;

import com.jt.www.biz.pay.service.PayOutService;
import com.jt.www.enums.woxuebao.PayOutStatusEnum;
import com.jt.www.model.reps.GenericDataResponse;
import com.jt.www.model.woxuebao.PayOutEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author shaoyn
 * @create 2020/02/19
 */
@Api(value = "支付超时校验入口", tags = {"PAY-OUT-API"}, description = "支付超时校验入口")
@RestController
@RequestMapping(value = "/pay/out")
public class PayOutController {

    public static final Logger log = LoggerFactory.getLogger(PayOutController.class);

    @Autowired
    PayOutService payOutService;

    @InitBinder
    public void initDateFormate(WebDataBinder dataBinder) {
        dataBinder.addCustomFormatter(new DateFormatter("yyyy-MM-dd HH:mm:ss"));
    }

    @ApiOperation(value = "投保时入库", notes = "投保时入库", httpMethod = "POST")
    @PostMapping(value = "/savePayOut")
    public ResponseEntity savePayOut(@RequestBody PayOutEntity payOutEntity) {
        if (null == payOutEntity || StringUtils.isBlank(payOutEntity.getApplicationFormCode())) {
            return GenericDataResponse.errorWithMsg("投保单号不能为空!");
        }
        Date date = payOutService.savePayOut(payOutEntity);
        return GenericDataResponse.okWithData(date);
    }


    /**
     * 手动检查支付超时接口
     */
    @ApiOperation(value = "手动检查支付超时", notes = "手动检查支付超时", httpMethod = "GET")
    @GetMapping(value = "/processPayOut")
    public void processPayOut() {
        List<PayOutEntity> list = payOutService.getNeedVerifyList();
        payOutService.processPayOut(list);
    }

    @ApiOperation(value = "查询超时时间", notes = "查询超时时间", httpMethod = "GET")
    @GetMapping(value = "/selectByAppCode")
    public ResponseEntity<GenericDataResponse<PayOutEntity>> selectByAppCode(@ApiParam(value = "投保单号", required = true) @RequestParam String appCode) {
        if (StringUtils.isBlank(appCode)) {
            return GenericDataResponse.errorWithMsg("投保单号不能为空!", PayOutEntity.class);
        }
        PayOutEntity payOut = payOutService.selectByAppCode(appCode);
        if (null == payOut) {
            return GenericDataResponse.errorWithMsg("该投保单未设置支付超时时间，请联系管理人员!", PayOutEntity.class);
        }
        if (PayOutStatusEnum.DEFAULT.getCode() == payOut.getStatus()
                && payOut.getPayOutTime().getTime() < System.currentTimeMillis()) {
            payOut.setStatus(PayOutStatusEnum.PAY_OUT.getCode());
        }
        return GenericDataResponse.okWithData(payOut);
    }


}
